package com.hex.ds.hdrs.app.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.hex.bigdata.hbda.base.Page;
import com.hex.bigdata.hbda.utils.SecurityUtils;
import com.hex.bigdata.hbda.utils.StringUtils;
import com.hex.ds.hdrs.agent.po.AgentConf;
import com.hex.ds.hdrs.agent.service.AgentConfService;
import com.hex.ds.hdrs.app.converter.IAppAdminRelationConverter;
import com.hex.ds.hdrs.app.converter.IAppAgentRelationConverter;
import com.hex.ds.hdrs.app.converter.IAppExecStrategyConverter;
import com.hex.ds.hdrs.app.converter.IAppGroupRelationConverter;
import com.hex.ds.hdrs.app.dao.AppConfDao;
import com.hex.ds.hdrs.app.dto.AppSessionResponseDto;
import com.hex.ds.hdrs.app.dto.AppAdminRelationDto;
import com.hex.ds.hdrs.app.dto.AppConfDto;
import com.hex.ds.hdrs.app.dto.AppGroupRelationDto;
import com.hex.ds.hdrs.app.po.*;
import com.hex.ds.hdrs.app.service.*;
import com.hex.ds.hdrs.app.vo.AppConfVo;
import com.hex.ds.hdrs.app.vo.AppSessionVO;
import com.hex.ds.hdrs.center.service.CenterManager;
import com.hex.ds.hdrs.common.annotation.AppCodeVerification;
import com.hex.ds.hdrs.common.constant.Const;
import com.hex.ds.hdrs.common.constant.DispatcherStrategy;
import com.hex.ds.hdrs.common.constant.ErrorCode;
import com.hex.ds.hdrs.common.exception.BizException;
import com.hex.ds.hdrs.common.helper.RamHelper;
import com.hex.ds.hdrs.common.utils.BaseUtil;
import com.hex.ds.hdrs.common.utils.HdrsDateUtil;
import com.hex.ds.hdrs.common.utils.MapUtil;
import com.hex.ds.hdrs.cron.po.CronTask;
import com.hex.ds.hdrs.cron.service.CronTaskDefService;
import com.hex.ds.hdrs.cron.service.CronTaskService;
import com.hex.ds.hdrs.engine.manager.ToRunManager;
import com.hex.ds.hdrs.period.job.service.PeriodJobDefService;
import com.hex.ds.hdrs.period.job.service.PeriodJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 应用定义表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2020-11-26
 */

@Slf4j
@Service
public class AppConfService {

    @Autowired
    private AppConfDao appConfDao;

    @Autowired
    private IAppGroupRelationService appGroupRelationService;

    @Autowired
    private IAppAgentRelationService appAgentRelationService;

    @Autowired
    private IAppAdminRelationService appAdminRelationService;

    @Autowired
    private IAppExecStrategyService appExecStrategyService;

    @Autowired
    private PeriodJobDefService periodJobDefService;

    @Autowired
    private PeriodJobService periodJobService;

    @Autowired
    private CronTaskDefService cronTaskDefService;

    @Autowired
    private CronTaskService cronTaskService;

    @Autowired
    private ToRunManager toRunManager;

    @Autowired
    private AppManager appManager;

    @Autowired
    private CenterManager centerManager;

    @Autowired
    private GroupConfService groupConfService;

    @Autowired
    private AgentConfService agentConfService;

    @Autowired
    private IAppAdminRelationConverter appAdminRelationConverter;

    @Autowired
    private IAppExecStrategyConverter appExecStrategyConverter;

    @Autowired
    private IAppGroupRelationConverter appGroupRelationConverter;

    @Autowired
    private IAppAgentRelationConverter appAgentRelationConverter;


    public AppConf qryAppConfByAppCode(String appCode) {
        return this.appConfDao.qryAppConfByAppCode(appCode);
    }

    /**
     * 通过agentCode 查询节点下面的应用
     *
     * @param agentCode
     * @return
     */
    public List<AppConf> qryAppConfByAgentCode(String agentCode) {
        return this.appConfDao.qryAppConfByAgentCode(agentCode);
    }

    /**
     * 查询所有应用
     *
     * @return
     */
    public List<AppConf> qryAppConfList() {
        return this.appConfDao.qryAppConfList();
    }


    /**
     * 分页查找
     *
     * @param appConf
     * @param page
     * @return
     */
    public List<AppConfVo> selectPages(AppConf appConf, Page page) {
        log.info("【进入AppConfService的selectPages】");
        Map map = MapUtil.convertObjToMap(appConf);
        return appConfDao.selectPages(map, page);

    }

    /**
     * 添加
     *
     * @param appConfDto
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void add(AppConfDto appConfDto) {
        log.info("【AppConfService.add】参数appConf: {}", appConfDto);
        int maxConcurrentNum = centerManager.getMaxConcurrentNum();

        maxConcurrentNum -= appConfDto.getConcurrentNum();
        this.checkLisenceForAddApp(maxConcurrentNum);

        // 保存app本身基本信息
        this.addNewApp(appConfDto);

        //与应用组建立关联
        AppGroupRelationDto appGroupRelationDto = appGroupRelationConverter.toAppGroupRelationDto(appConfDto);
        this.appGroupRelationService.add(appGroupRelationDto);
        //与Agent建立关联
        this.appAgentRelationService.add(appConfDto.getNodes(),appConfDto.getAppCode());
        //保存自定义策略信息
        this.appExecStrategyService.add(appConfDto.getExecStrategys(), appConfDto.getAppCode());
        //保存管理员信息
        AppAdminRelationDto appAdminRelationDto = appAdminRelationConverter.toAppAdminRelationDto(appConfDto);
        this.appAdminRelationService.addAdmin(appAdminRelationDto);

        //新增appSession
        appManager.createAppSession(appConfDto, toRunManager);
    }

    /**
     * @Method: checkLisenceForAddApp
     * @Param: [maxConcurrentNum]
     * @Return: void
     * @Description： 新增app，校验lisence
     * @Author： jd.chen
     * @Date： 2021/6/24 16:52
     * @Version： V1.0
     */
    public void checkLisenceForAddApp(int maxConcurrentNum) {
        // 校验并发数是否超过限制
        int concurrentNum = this.appConfDao.qryConcurrentNum();
        if (concurrentNum >= maxConcurrentNum) {
            log.error("应用总并发数超过限制数，不允许添加！");
            throw new BizException(ErrorCode.ERROR_840005);
        }
    }

    /**
     * 添加新的应用
     *
     * @param appConfDto
     */
    private void addNewApp(AppConfDto appConfDto) {
        appConfDto.setPkId(BaseUtil.getPkId());
        appConfDto.setCrtUser(SecurityUtils.getUsername());
        appConfDto.setCrtTs(HdrsDateUtil.getCurrentTime());
        appConfDto.setUpTs(HdrsDateUtil.getCurrentTime());
        appConfDto.setUpUser(SecurityUtils.getUsername());
        appConfDto.setAppSatus(Const.APP_STATUS_STOP);
        this.appConfDao.add(appConfDto);
    }

    /**
     * 删除
     *
     * @param list
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void del(List<String> list) {
        log.info("【AppConfService.del】参数List<AppConf> list: {}", list.toString());
        if (CollectionUtil.isEmpty(list)) {
            throw new BizException(ErrorCode.ERROR_910001);
        }
        for (String pkId : list) {
            AppConfDto appConf = this.getAppConfDto("pkId", pkId);
            if (checkAppHasUsed(appConf.getAppCode())) {
                throw new BizException("910001", "应用【" + appConf.getAppName() + "】在关联表中存在，无法删除");
            } else {
                this.deleteApp(appConf.getAppCode(), pkId);
            }
        }
    }

    /**
     * 删除应用相关信息
     *
     * @param appCode
     * @param pkId
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteApp(String appCode, String pkId) {
        this.appGroupRelationService.deleteByAppCode(appCode);
        this.appAdminRelationService.removeByAppCode(appCode);
        this.appAgentRelationService.deleteByAppCode(appCode);
        this.appExecStrategyService.deleteByAppCode(appCode);
        this.appConfDao.del(pkId);
    }

    /**
     * 判断应用是否允许删除
     *
     * @param appCode
     * @return
     */
    private boolean checkAppHasUsed(String appCode) {
        //1.判断周期作业（表period_job）中是否有引用该应用
        if (periodJobDefService.getPeriodJobDefListByAppCode(appCode) > 0) {
            return true;
        }
        //2.判断周期作业实例中是否有引用该应用
        if (CollectionUtil.isNotEmpty(periodJobService.queryListByAppCode(appCode))) {
            return true;
        }
        //3.判断定时任务中是否有引用该应用
        if (cronTaskDefService.queryListByAppCode(appCode).size() > 0) {
            return true;
        }
        //4.判断定时任务实例中是否引用该应用
        CronTask cronTask = new CronTask();
        cronTask.setAppCode(appCode);
        if (this.cronTaskService.qryTaskList(cronTask).size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 查询appCode和appName
     *
     * @return
     */
    public List<AppConf> qryCodeName() {
        return this.appConfDao.qryCodeName();
    }


    /**
     * 修改应用状态
     *
     * @param appSatus
     * @param appCode
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void editAppSatus(String appSatus, String appCode) {
        AppConf appConf = new AppConf();
        appConf.setAppSatus(appSatus);
        appConf.setAppCode(appCode);
        int res = this.appConfDao.editAppSatus(appConf);
        if (res > 0) {
            appManager.updateAppStatus(appSatus, appCode);
        }
    }

    /**
     * @Method: getAppConfDto
     * @Param: [fieldName, value]
     * @Return: com.hex.ds.hdrs.app.model.dto.AppConfDto
     * @Description： 查询获取应用扩展信息
     * @Author： jd.chen
     * @Date： 2021/6/24 17:10
     * @Version： V1.0
     */
    public AppConfDto getAppConfDto(String fieldName, String value) {
        Map map = new HashMap<>(16);
        map.put(fieldName, value);
        return this.appConfDao.qryAppConfDto(map);
    }

    /**
     * 获取某个应用信息
     *
     * @param pkId
     * @return
     */
    public AppConfDto getEdit(String pkId) {
        log.info("【AppConfService.getEdit】pkId: {}", pkId);
        AppConfDto appConfDto = this.getAppConfDto("pkId", pkId);
        List<AppAgentRelationPo> appAgentRelationPoList = appAgentRelationService.queryListByAppCode(appConfDto.getAppCode());
        appConfDto.setNodes(appAgentRelationConverter.toAppAgentRelationDtos(appAgentRelationPoList));

        List<AppExecStrategyPo> appExecStrategyPoDtoList = appExecStrategyService.queryListByAppCode(appConfDto.getAppCode());
        appConfDto.setExecStrategys(appExecStrategyConverter.toAppExecStrategyDtoList(appExecStrategyPoDtoList));

        this.getAllAdminUser(appConfDto);
        return appConfDto;
    }

    /**
     * 获取全部管理员
     *
     * @param appConfDto
     */
    private void getAllAdminUser(AppConfDto appConfDto) {
        AppAdminRelationDto appAdminRelationDto = appAdminRelationConverter.toAppAdminRelationDto(appConfDto);
        List<AppAdminRelationPo> appAdminRelationPoList = appAdminRelationService.queryList(appAdminRelationDto);
        List<String> devList = new ArrayList();
        List<String> monitorList = new ArrayList();
        List<String> relList = new ArrayList();
        if (!CollectionUtil.isEmpty(appAdminRelationPoList)) {
            for (AppAdminRelationPo appAdminRelationPo : appAdminRelationPoList) {
                if ("1".equals(appAdminRelationPo.getAdminType())) {
                    devList.add(appAdminRelationPo.getAdminUserCode());
                }
                if ("2".equals(appAdminRelationPo.getAdminType())) {
                    monitorList.add(appAdminRelationPo.getAdminUserCode());
                }
                if ("3".equals(appAdminRelationPo.getAdminType())) {
                    relList.add(appAdminRelationPo.getAdminUserCode());
                }
            }
        }
        appConfDto.setDevAdmins(devList);
        appConfDto.setMonitorAdmins(monitorList);
        appConfDto.setReleaseAdmins(relList);
    }

    /**
     * 修改应用
     *
     * @param appConfDto
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateAppConf(AppConfDto appConfDto) {
        log.info("【AppConfService.updateAppConf】【{}】", appConfDto.toString());
        appConfDto.setUpTs(HdrsDateUtil.getCurrentTime());
        appConfDto.setUpUser(SecurityUtils.getUsername());
        this.appConfDao.edit(appConfDto);
        AppAdminRelationDto appAdminRelationDto = appAdminRelationConverter.toAppAdminRelationDto(appConfDto);
        appAdminRelationService.modifyByAppCode(appAdminRelationDto);
    }

    /**
     * 修改应用
     *
     * @param appConfDto
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void edit(AppConfDto appConfDto) {
        log.info("【AppConfService.edit】【{}】", appConfDto.toString());
        appConfDto.setUpTs(HdrsDateUtil.getCurrentTime());
        appConfDto.setUpUser(SecurityUtils.getUsername());
        this.appConfDao.edit(appConfDto);

        AppGroupRelationDto appGroupRelationDto = appGroupRelationConverter.toAppGroupRelationDto(appConfDto);
        this.appGroupRelationService.modifyByAppCode(appGroupRelationDto);
        this.appAgentRelationService.modifyByAppCode(appConfDto.getNodes(), appConfDto.getAppCode());
        this.appExecStrategyService.modifyByAppCode(appConfDto.getExecStrategys(), appConfDto.getAppCode());
        AppAdminRelationDto appAdminRelationDto = appAdminRelationConverter.toAppAdminRelationDto(appConfDto);
        appAdminRelationService.modifyByAppCode(appAdminRelationDto);
        updateAppRamData(appConfDto);
    }

    /*
     * @Method: updateAppRamData <br>
     * @Param: [appConfDto] <br>
     * @Return: void <br>
     * @Description：更新App内存数据<br>
     * @Author： wz.li<br>
     * @Date： 2022/11/24 20:04 <br>
     * @Version： V2.0.2<br>
     */
    private void updateAppRamData(AppConfDto appConfDto){
        //更新appConf
        AppSession appSession = appManager.getAppSession(appConfDto.getAppCode());
        // TODO 如果应用授权的调度服务有变更，比如新增、删除、修改权权重，没有更新Appsession中的信息，更新了后果会怎样，需要分析下后果
        if (appSession != null){
            appSession.setAppConf(appConfDto);
            //更新appGroup信息
            updateAppGroupRamData(appConfDto);
            //更新权重agentWeightMap
            Map<String, Integer> agentWeightMap = appManager.getAgentWeightMap(appConfDto.getAppCode());
            appSession.setAgentWeightMap(agentWeightMap);
            //更新自定义策略execStrategyList
            List<AppExecStrategyPo> appExecStrategyPoList = this.appExecStrategyService.queryListByAppCode(appConfDto.getAppCode());
            appSession.setExecStrategyList(appExecStrategyPoList);

            List<AgentConf> agentConfList = agentConfService.qryAgentConfByAppCode(appConfDto.getAppCode());
            appManager.updateAgentConf(agentConfList, appConfDto);
        }
    }

    /*
     * @Method: updateAppGroupRamData <br>
     * @Param: [appConfDto] <br>
     * @Return: void <br>
     * @Description：更新应用组内存信息<br>
     * @Author： wz.li<br>
     * @Date： 2022/11/24 20:06 <br>
     * @Version： V2.0.2<br>
     */
    private void updateAppGroupRamData(AppConfDto appConfDto){
        if (StringUtils.isNotBlank(appConfDto.getGroupCode())) {
            Map<String, List<AppConf>> appGroup = appManager.getAppGroup();
            List<AppConf> findAppByGroupCode = this.findAppByGroupCode(appConfDto.getGroupCode());
            appGroup.put(appConfDto.getGroupCode(), findAppByGroupCode);
        }
    }

    /**
     * 获取当前用户所属的应用
     *
     * @return
     */
    public List<AppConf> findAppByCurrentUser(String username) {
        log.info("【AppConfService.findAppByCurrentUser】参数username: {}", username);
        if ("admin".equals(username)) {
            username = null;
        }
        return this.appConfDao.findAppByCurrentUser(username);
    }

    /**
     * 查重
     *
     * @param appConf
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean checkAppData(AppConf appConf) {
        log.info("【AppConfService.checkAppData】参数appConf: {}", appConf.toString());
        Map map = MapUtil.convertObjToMap(appConf);
        AppConf dbAppConf = this.appConfDao.getAppConf(map);
        if (dbAppConf != null && !dbAppConf.getPkId().equals(appConf.getPkId())) {
            return false;
        }
        return true;
    }

    /**
     * 通过appCode查询应用组件信息
     *
     * @return
     */
    @AppCodeVerification(paramObject = String.class)
    public AppConfDto findAppConfDtoByAppCode(String appCode) {
        log.info("【AppConfService.findAppConfByAppCode】");
        AppConfDto appConfDto = this.getAppConfDto("appCode", appCode);

        List<AppAgentRelationPo> appAgentRelationPoList = appAgentRelationService.queryListByAppCode(appCode);
        appConfDto.setNodes(appAgentRelationConverter.toAppAgentRelationDtos(appAgentRelationPoList));

        List<AppExecStrategyPo> appExecStrategyPoDtoList = appExecStrategyService.queryListByAppCode(appConfDto.getAppCode());
        appConfDto.setExecStrategys(appExecStrategyConverter.toAppExecStrategyDtoList(appExecStrategyPoDtoList));

        this.getAllAdminUser(appConfDto);
        return appConfDto;
    }


    /**
     * 获取某个用户所属的sppCode
     *
     * @param username
     * @return
     */
    public List<String> findAppCodeByUser(String username) {
        return this.appConfDao.findAppCodeByUser(username);
    }

    /**
     * 根据groupCode查询应用
     *
     * @param groupCode
     * @return
     */
    public List<AppConf> findAppByGroupCode(String groupCode) {
        return this.appConfDao.findAppByGroupCode(groupCode);
    }

    public Integer qryAppCount(Map map) {
        return this.appConfDao.qryAppCount(map);
    }

    public List<AppConf> findCodeByName(String appName) {
        return this.appConfDao.findCodeByName(appName);
    }

    /**
     * @Method: getCurrentAppInf
     * @Param: []
     * @Return: com.hex.ds.hdrs.app.dto.AppConfDto
     * @Description： 获取当前应用的基本信息
     * @Author： jd.chen
     * @Date： 2021/7/12 19:11
     * @Version： V1.0
     */
    @AppCodeVerification(paramObject = String.class)
    public AppConfDto getCurrentAppInf(String appCode) {
        AppConfDto appConfDto = getAppConfDto("appCode", appCode);
        GroupConf groupConf = groupConfService.qryGroupCodeByGroupCode(appConfDto.getGroupCode());
        if (groupConf != null) {
            appConfDto.setGroupName(groupConf.getGroupName());
        }
        if (StrUtil.isNotBlank(appConfDto.getDispatcherStrategyCode())) {
            appConfDto.setDispatcherStrategyName(DispatcherStrategy.getValueByCode(appConfDto.getDispatcherStrategyCode()));
        }
        List<AppExecStrategyPo> appExecStrategyPoList = appExecStrategyService.queryListByAppCode(appCode);
        AppExecStrategyPo appExecStrategyPo = getAppStrategy(appExecStrategyPoList);
        if (appExecStrategyPo != null){
            appConfDto.setResNum(appExecStrategyPo.getResNum());
            appConfDto.setConcurrentNum(appExecStrategyPo.getConcurrentNum());
        }
        appConfDto.setLastUpdateTime(HdrsDateUtil.getCurrentTime());
        if (appManager.getValidAppSession(appCode) != null) {
            Integer resNumUsage = appManager.getValidAppSession(appCode).getCurResNum().get();
            Integer conNumUssge = appManager.getValidAppSession(appCode).getCurConcurrentNum().get();
            appConfDto.setResNumUsage(resNumUsage);
            appConfDto.setConNumUssge(conNumUssge);

            appConfDto.setResUsageRate(resNumUsage * 100 / appConfDto.getResNum());
            appConfDto.setConUsageRate(conNumUssge * 100 / appConfDto.getConcurrentNum());
        }
        return appConfDto;
    }

    public AppExecStrategyPo getAppStrategy(List<AppExecStrategyPo> appExecStrategyPoList) {
        if (CollectionUtil.isNotEmpty(appExecStrategyPoList)){
            int hour = HdrsDateUtil.getHour();
            for (AppExecStrategyPo strategy : appExecStrategyPoList) {
                int stHour = Integer.parseInt(strategy.getStHour().split(":")[0]);
                int endHour = Integer.parseInt(strategy.getEndHour().split(":")[0]);
                if (hour >= stHour && hour <= endHour) {
                    return strategy;
                }
            }
        }
        return null;
    }

    /**
     * 查询内存有效应用
     *
     * @param appSession
     * @param page
     * @return
     */
    public List<AppSessionVO> qryAppSession(AppSessionVO appSession, Page page) {
        List<AppSessionVO> appSessionVOList = new ArrayList<AppSessionVO>();
        List<AppSession> appSessionList = appManager.getAppSessionList();
        List<AppSession> appSessionListShow = new ArrayList<AppSession>();
        // 条件过滤
        if (org.apache.commons.lang3.StringUtils.isNotBlank(appSession.getAppCode())) {
            for (AppSession appSession2 : appSessionList) {
                if (appSession2.getAppCode().equals(appSession.getAppCode())) {
                    appSessionListShow.add(appSession2);
                }
            }
        } else {
            appSessionListShow = appSessionList;
        }
        for (AppSession appSession2 : appSessionListShow) {
            AppSessionVO appSessionVO = new AppSessionVO();
            appSessionVO.setAppCode(appSession2.getAppCode());
            appSessionVO.setAppStatus(appSession2.getAppStatus());
            appSessionVO.setSortStrategy(appSession2.getSortStrategy());
            appSessionVO.setWeightType(appSession2.getWeightType());
            appSessionVO.setWeight(String.valueOf(appSession2.getWeight()));
            appSessionVOList.add(appSessionVO);
        }
        // 结果分页
        return RamHelper.formatAppListPage(appSessionVOList, page);
    }

    /**
     * 查询内存无效应用
     *
     * @param appSession
     * @param page
     * @return
     */
    public List<AppSessionVO> qryNotValidAppSession(AppSessionVO appSession, Page page) {
        List<AppSessionVO> appSessionVOList = new ArrayList<AppSessionVO>();
        List<AppSession> appSessionList = appManager.getNotValidAppSessionList();
        List<AppSession> appSessionListShow = new ArrayList<AppSession>();

        // 条件过滤
        if (org.apache.commons.lang3.StringUtils.isNotBlank(appSession.getAppCode())) {
            for (AppSession appSession2 : appSessionList) {
                if (appSession2.getAppCode().equals(appSession.getAppCode())) {
                    appSessionListShow.add(appSession2);
                }
            }
        } else {
            appSessionListShow = appSessionList;
        }
        for (AppSession appSession2 : appSessionListShow) {
            AppSessionVO appSessionVO = new AppSessionVO();
            appSessionVO.setAppCode(appSession2.getAppCode());
            appSessionVO.setAppStatus(appSession2.getAppStatus());
            appSessionVO.setSortStrategy(appSession2.getSortStrategy());
            appSessionVO.setWeightType(appSession2.getWeightType());
            appSessionVO.setWeight(String.valueOf(appSession2.getWeight()));
            appSessionVOList.add(appSessionVO);
        }
        // 结果分页
        return RamHelper.formatAppListPage(appSessionVOList, page);
    }

    /**
     * 查询内存应用map
     *
     * @param appSession
     * @param page
     * @return
     */
    public List<AppSessionVO> qryAppSessionMap(AppSessionVO appSession, Page page) {
        List<AppSessionVO> appSessionVOList = new ArrayList<AppSessionVO>();
        List<AppSession> appSessionList = new ArrayList<AppSession>();
        List<AppSession> appSessionListShow = new ArrayList<AppSession>();
        Map<String, AppSession> appSessionMap = appManager.getAppSessionMap();
        for (String appCode : appSessionMap.keySet()) {
            appSessionList.add(appManager.getAppSession(appCode));
        }

        // 条件过滤
        if (org.apache.commons.lang3.StringUtils.isNotBlank(appSession.getAppCode())) {
            for (AppSession appSession2 : appSessionList) {
                if (appSession2.getAppCode().equals(appSession.getAppCode())) {
                    appSessionListShow.add(appSession2);
                }
            }
        } else {
            appSessionListShow = appSessionList;
        }
        for (AppSession appSession2 : appSessionListShow) {
            AppSessionVO appSessionVO = new AppSessionVO();
            appSessionVO.setAppCode(appSession2.getAppCode());
            appSessionVO.setAppStatus(appSession2.getAppStatus());
            appSessionVO.setSortStrategy(appSession2.getSortStrategy());
            appSessionVO.setWeightType(appSession2.getWeightType());
            appSessionVO.setWeight(String.valueOf(appSession2.getWeight()));
            appSessionVOList.add(appSessionVO);
        }
        // 结果分页
        return RamHelper.formatAppListPage(appSessionVOList, page);
    }

    public AppSessionResponseDto qryAppSessionInfo(String appCode){
        AppSession appSession = appManager.getAppSession(appCode);
        AppSessionResponseDto appSessionResponseDto = new AppSessionResponseDto();
        if (appSession != null){
            appSessionResponseDto.setAppCode(appSession.getAppCode());
            appSessionResponseDto.setAppName(appSession.getAppName());
            appSessionResponseDto.setAppStatus(appSession.getAppStatus());
            appSessionResponseDto.setSortStrategy(appSession.getSortStrategy());
            appSessionResponseDto.setExecStrategyList(appSession.getExecStrategyList());
            appSessionResponseDto.setAgentConfList(appSession.getAgentConfList());
            appSessionResponseDto.setCurResNum(appSession.getCurResNum().get());
            appSessionResponseDto.setCurConcurrentNum(appSession.getCurConcurrentNum().get());
            appSessionResponseDto.setPeriodRunningList(appSession.getPeriodRunningList());
            appSessionResponseDto.setCronRunningList(appSession.getCronRunningList());

            List<AppExecStrategyPo> appExecStrategyPoList = appExecStrategyService.queryListByAppCode(appCode);
            AppExecStrategyPo appExecStrategyPo = getAppStrategy(appExecStrategyPoList);
            if (appExecStrategyPo != null){
                appSessionResponseDto.setResTotal(appExecStrategyPo.getResNum());
                appSessionResponseDto.setConcurrentTotal(appExecStrategyPo.getConcurrentNum());
                appSessionResponseDto.setResUsageRate(appSessionResponseDto.getCurResNum() * 100 / appSessionResponseDto.getResTotal());
                appSessionResponseDto.setConUsageRate(appSessionResponseDto.getCurConcurrentNum() * 100 / appSessionResponseDto.getConcurrentTotal());
            }
        }
        return appSessionResponseDto;
    }

    public List<AppConf> findAppConfListByCurrentUser(Map map) {
        return this.appConfDao.findAppConfListByCurrentUser(map);
    }
}
